/**
 *
 * @param url 下载地址
 * @param filename 自定义文件名
 */
export function download(url, filename) {
	getBlob(url, function(blob) {
		saveAs(blob, filename)
	})
}


function getBlob(url, cb) {
	const xhr = new XMLHttpRequest()
	xhr.open('GET', url, true)
	xhr.responseType = 'blob'
	xhr.onload = function() {
		if (xhr.status === 200) {
			cb(xhr.response)
		}
	}
	xhr.send()
}

function saveAs(blob, filename) {
	if (window.navigator.msSaveOrOpenBlob) {
		navigator.msSaveBlob(blob, filename)
	} else {
		const link = document.createElement('a')

		const body = document.querySelector('body')

		link.href = window.URL.createObjectURL(blob)

		link.download = filename

		link.style.display = 'none'

		body.appendChild(link)

		link.click()

		body.removeChild(link)

		window.URL.revokeObjectURL(link.href)
	}
}

/**
 * 保存文件
 * @param data
 * @param fileName
 */
export function saveFile(data, fileName) {
	var isIE11 =
		navigator.userAgent.indexOf('Trident') > -1 && navigator.userAgent.indexOf('rv:11.0') > -1
	if (isIE11) {
		window.navigator.msSaveOrOpenBlob(data, fileName)
	} else {
		const export_blob = new Blob([data])
		const save_link = document.createElement('a')
		document.body.appendChild(save_link)
		save_link.style.display = 'none'
		save_link.href = window.URL.createObjectURL(export_blob)
		save_link.download = fileName
		save_link.click()
		document.body.removeChild(save_link)
	}
}
